import json

from django.http import HttpResponse
from django.shortcuts import render
from django.views import View

from apps.menu.models import MainMenu, SubMenu
from utils import ResponseMessage


# Create your views here.


class GoodsMainMenu(View):
    """
    处理商品主菜单请求的类
    继承自Django的View类，响应HTTP的GET和POST请求
    """


def get(self, request):
    """
    处理GET请求的方法:
    :param request: HTTP请求对象，包含请求信息
    :return: 返回商品主菜单的响应信息
    """
    # 查询数据库中所有的主菜单项
    main_menu = MainMenu.objects.all()

    result_list = []
    # result_json = {}
    # 遍历查询到的主菜单项，将其转换为字符串后加入结果列表
    for m in main_menu:
        result_list.append(m.__str__())

    # result_json['status'] = 1000
    # result_json['data'] = result_list
    #
    # return HttpResponse(json.dumps(result_json), content_type='application/json')
    # 使用自定义的响应消息类返回成功消息和数据
    return ResponseMessage.MenuResponseMessage.success(result_list)


# def post(self, request):
#     print('post请求来了')
#     return HttpResponse('POST请求来了')


class GoodsSubMenu(View):
    # 处理商品子菜单请求的类,继承自Django的View类，用于处理HTTP GET请求，返回商品子菜单信息
    def get(self, request):
        # 获取请求参数
        param_id = request.GET['main_menu_id']
        # 根据请求参数获取二级菜单内容
        sub_menu = SubMenu.objects.filter(main_menu_id=param_id)

        result_list = []
        # result_json = {}
        # 遍历子菜单查询结果，将每个子菜单的字符串表示添加到结果列表
        for m in sub_menu:
            result_list.append(m.__str__())

        # result_json['status'] = 1000
        # result_json['data'] = result_list

        return ResponseMessage.MenuResponseMessage.success(result_list)
